<template>
  <div class="container">
    <div class="map-data-list">
      <div class="search-wrapper">
        <el-form :model="pathInfo" label-width="86px" ref="ruleForm">
          <el-form-item
            label="始发地："
            prop="start"
            :rules="{
              required: true,
              message: '始发地不能为空',
              trigger: 'blur',
            }"
          >
            <el-input
              class="map-input-add"
              v-model="pathInfo.start"
              @focus="changeCity('start')"
              @input="keywordsSearch"
            ></el-input>
            <i class="el-icon-plus add-icon" @click="addPath"></i>
          </el-form-item>
          <el-form-item
            v-for="(v, i) in pathInfo.morePath"
            :key="v.path + i"
            label="经过地："
          >
            <el-input
              class="map-input-add"
              v-model="pathInfo.morePath[i].path"
              @focus="changeCity(i)"
              @input="keywordsSearch"
            ></el-input>
            <i class="el-icon-minus add-icon" @click="deletePath(i)"></i>
          </el-form-item>
          <el-form-item
            label="目的地："
            prop="end"
            :rules="{
              required: true,
              message: '目的地不能为空',
              trigger: 'blur',
            }"
          >
            <el-input
              class="map-input-add"
              v-model="pathInfo.end"
              @focus="changeCity('end')"
              @input="keywordsSearch"
            >
            </el-input>
          </el-form-item>
          <div class="btn-wrapper">
            <el-button class="center-btn" type="primary" @click="createRoute"
              >搜索</el-button
            >
            <div></div>
            <!-- <el-button class="center-btn" type="primary" @click="allPathInfo"
              >复制路线</el-button
            > -->
            <el-button class="center-btn" type="primary" @click="submit"
              >保存路线</el-button
            >
          </div>
        </el-form>
      </div>
      <div class="line"></div>
      <el-scrollbar class="scrollbar-wrapper">
        <div class="data-list">
          <div class="drivecircuits">
            <div
              class="data-wrapper"
              v-for="(v, i) in cityList"
              :key="i"
              @click="setPosition(v)"
            >
              <div class="path-title">{{ v.name }} {{ v.address }}</div>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </div>
    <div
      class="map-wrapper"
      v-loading="loading"
      element-loading-text="路线载入中..."
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.6)"
    >
      <div id="map"></div>
    </div>
    <el-dialog
      class="dialog-wrapper"
      title="提示"
      :visible.sync="isShow"
      width="38%"
    >
      <el-form :model="saveInfo" label-width="96px" ref="saveForm">
        <el-form-item
          label="整车尺寸："
          :rules="{
            required: true,
            message: '不能为空',
            trigger: 'blur',
          }"
        >
          <el-form-item
            class="little-wrapper"
            prop="long"
            :rules="{
              required: true,
              message: '长度不能为空',
              trigger: 'blur',
            }"
          >
            <el-input
              class="little-input"
              placeholder="长度"
              v-model="saveInfo.long"
            >
            </el-input>
            <span class="unit"> X </span>
          </el-form-item>
          <el-form-item
            class="little-wrapper"
            prop="wide"
            :rules="{
              required: true,
              message: '宽度不能为空',
              trigger: 'blur',
            }"
          >
            <el-input
              class="little-input"
              placeholder="宽度"
              v-model="saveInfo.wide"
            >
            </el-input>
            <span class="unit"> X </span>
          </el-form-item>
          <el-form-item
            class="little-wrapper"
            prop="high"
            :rules="{
              required: true,
              message: '高度不能为空',
              trigger: 'blur',
            }"
          >
            <el-input
              class="little-input"
              placeholder="高度"
              v-model="saveInfo.high"
            >
            </el-input>
          </el-form-item>
        </el-form-item>
        <el-form-item
          class="little-wrapper"
          label="吨位："
          prop="tonnage"
          :rules="{
            required: true,
            message: '吨位不能为空',
            trigger: 'blur',
          }"
        >
          <el-input
            class="little-input"
            placeholder="吨位"
            v-model="saveInfo.tonnage"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label="路线类型："
          prop="routetype"
          :rules="{
            required: true,
            message: '路线类型不能为空',
            trigger: 'blur',
          }"
        >
          <el-select
            class="route-type"
            v-model="saveInfo.routetype"
            placeholder="请选择路线类型"
          >
            <el-option
              v-for="(v, k) in routeTypes"
              :key="k"
              :label="v"
              :value="k"
            >
              {{ v }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="时间："
          prop="time"
          :rules="{
            required: true,
            message: '时间不能为空',
            trigger: 'blur',
          }"
        >
          <el-date-picker
            class="time-wrapper"
            v-model="saveInfo.time"
            type="datetimerange"
            range-separator="至"
            value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="路线备注："
          prop="locationdescriptioninchinese"
          :rules="{
            required: true,
            message: '路线备注不能为空',
            trigger: 'blur',
          }"
        >
          <el-input
            type="textarea"
            :rows="6"
            placeholder="请输入路线备注信息"
            v-model="saveInfo.locationdescriptioninchinese"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelDialog">取 消</el-button>
        <el-button type="primary" @click="saveData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import { addDrivecircuit } from "@/api/system/drivecircuit";

export default {
  data() {
    return {
      pathInfo: {
        start: "",
        end: "",
        morePath: [],
      },
      dataInfo: {
        start: "",
        end: "",
        morePath: [],
      },
      routeTypes: {
        0: "省内",
        1: "省外",
      },
      loading: false,
      map: null,
      driving: null,
      curType: "start",
      aMap: null,
      cityList: [],
      searchOptions: {
        city: "全国",
        pageIndex: 1,
        pageSize: 50,
      },
      saveInfo: {
        long: "",
        wide: "",
        high: "",
        time: [],
        tonnage: "",
        routetype: "",
        locationdescriptioninchinese: "",
      },
      isShow: false,
      allPath: [],
      num: 0,
      markers: {},
      route: [],
      sort: {},
      routers: [],
      geocoder: null,
      dragRoute: null,
    };
  },
  methods: {
    cancelDialog() {
      this.isShow = false;
      this.saveInfo.locationdescriptioninchinese = "";
    },
    allPathInfo() {
      let _this = this;
      let { start, morePath, end } = this.pathInfo;
      let route = "";
      morePath.map((v) => {
        route += v.path + "-";
      });
      let str = start + "-" + route + end;
      this.$copyText(str).then(
        function () {
          _this.$message.success("复制成功");
        },
        function () {
          _this.$message.error("复制失败");
        }
      );
    },
    deletePath(index) {
      this.cityList = [];
      this.pathInfo.morePath.splice(index, 1);
      this.dataInfo.morePath.splice(index, 1);
    },
    addPath() {
      this.cityList = [];
      this.pathInfo.morePath.push({ path: "" });
      this.dataInfo.morePath.push({});
    },
    changeCity(type) {
      this.curType = type;
      this.cityList = [];
      // if (this.curType == 'start' || this.curType == 'end')
      //   this.keywordsSearch(this.pathInfo[this.curType])
      // else this.keywordsSearch(this.pathInfo.morePath[this.curType])
    },
    setPosition(data) {
      let { location, name, address } = data;
      if (this.curType == "start" || this.curType == "end")
        this.dataInfo[this.curType] = {};
      this.markers[this.curType] && this.markers[this.curType].setMap(null);
      let marker = new this.aMap.Marker({
        position: [location.lng, location.lat],
        map: this.map,
      });
      marker.setMap(this.map);
      this.map.setFitView([marker]);
      this.markers[this.curType] = marker;
      if (this.curType == "start" || this.curType == "end") {
        this.dataInfo[this.curType] = data;
        // this.pathInfo[this.curType] = name+' '+address
      } else {
        if (
          this.dataInfo.morePath[this.curType] &&
          this.pathInfo.morePath[this.curType]
        ) {
          this.dataInfo.morePath[this.curType] = data;
          this.pathInfo.morePath[this.curType].path = name + " " + address;
        } else {
          this.dataInfo.morePath.push(data);
          this.pathInfo.morePath.push({ path: name + " " + address });
        }
      }
    },
    saveData() {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          let { start, end, morePath } = this.dataInfo;
          let {
            long,
            wide,
            high,
            time,
            tonnage,
            routetype,
            locationdescriptioninchinese,
          } = this.saveInfo;
          let data = [];
          let startInfo = [[start.location.lng, start.location.lat]];
          let endInfo = [[end.location.lng, end.location.lat]];
          let centerArr = morePath.reduce(
            (pre, cur) => pre.concat([[cur.location.lng, cur.location.lat]]),
            []
          );
          data = [...startInfo, ...centerArr, ...endInfo];
          addDrivecircuit({
            carsize: long + "*" + wide + "*" + high,
            routestarttime: time[0],
            routeendtime: time[1],
            routetype,
            tonnage,
            startname: this.pathInfo.start,
            startlongitude: this.dataInfo.start.location.lng,
            startlatitude: this.dataInfo.start.location.lat,
            destinationname: this.pathInfo.end,
            destinationlongitude: this.dataInfo.end.location.lng,
            destinationlatitude: this.dataInfo.end.location.lat,
            locationdescriptioninchinese,
            pointposition: JSON.stringify(data),
          }).then(({ code }) => {
            if (code == 200) {
              this.map.clearMap();
              this.$message.success("新增路线成功");
              this.clearData();
              this.isShow = false;
            } else this.$message.error("网络错误");
          });
        } else return false;
      });
    },
    submit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.pathInfo.start && !this.dataInfo.start) {
            this.$message.error("请选择精确的出发地");
            return false;
          }
          if (this.pathInfo.end && !this.dataInfo.end) {
            this.$message.error("请选择精确的目的地");
            return false;
          }
          for (let i = 0; i < this.pathInfo.morePath.length; i++) {
            if (!Object.keys(this.dataInfo.morePath[i]).length) {
              this.$message.error("请选择精确的第" + (i + 1) + "项经过地");
              return false;
            }
          }
          this.isShow = true;
        } else return false;
      });
    },
    clearData() {
      this.pathInfo = {
        start: "",
        end: "",
        morePath: [],
      };
      this.dataInfo = {
        start: "",
        end: "",
        morePath: [],
      };
      this.saveInfo = {
        long: "",
        wide: "",
        high: "",
        time: [],
        tonnage: "",
        routetype: "",
        locationdescriptioninchinese: "",
      };
      this.cityList = [];
      this.saveInfo.locationdescriptioninchinese = "";
    },
    createRoute() {
      if (this.pathInfo.start && !this.dataInfo.start) {
        this.$message.error("请选择精确的出发地");
        return false;
      }
      if (this.pathInfo.end && !this.dataInfo.end) {
        this.$message.error("请选择精确的目的地");
        return false;
      }
      for (let i = 0; i < this.pathInfo.morePath.length; i++) {
        if (!Object.keys(this.dataInfo.morePath[i]).length) {
          this.$message.error("请选择精确的第" + (i + 1) + "项经过地");
          return false;
        }
      }
      if (this.loading) {
        this.$message.warning("路线载入中,请稍后更换线路...");
        return false;
      }
      this.cityList = [];
      let startLocation = this.dataInfo.start.location;
      let endLocation = this.dataInfo.end.location;
      this.allPath = this.dataInfo.morePath.reduce(
        (pre, cur) => pre.concat([[cur.location.lng, cur.location.lat]]),
        []
      );
      this.loading = true;
      this.map.clearMap();
      this.route = [
        [startLocation.lng, startLocation.lat],
        ...this.allPath,
        [endLocation.lng, endLocation.lat],
      ];
      this.search();
    },
    search() {
      this.routers = [];
      this.sort = {};
      this.num = 0;
      let _this = this;
      for (let i = 0; i < this.route.length; i++) {
        let item = this.route[i];
        this.routers.push(new AMap.LngLat(item[0], item[1]));
      }
      this.dragRoute = new this.aMap.DragRoute(
        this.map,
        this.routers,
        AMap.DrivingPolicy.LEAST_FEE
      );
      this.dragRoute.search();
      this.dragRoute.on("complete", function ({ data }) {
        _this.setRoute(data);
        _this.loading = false;
      });
    },
    getCityName(location) {
      return new Promise((resolve, reject) => {
        this.geocoder.getAddress(location, function (status, { regeocode }) {
          if (status === "complete") resolve(regeocode.formattedAddress);
          else resolve();
        });
      });
    },
    setRoute({ start, waypoints, end }) {
      this.pathInfo.morePath = [];
      let data = { start, morePath: waypoints, end };
      for (let i in data) {
        if (i !== "morePath") {
          this.dataInfo[i] = data[i];
        } else {
          for (let j = 0; j < data[i].length; j++) {
            this.pathInfo[i].push({ path: "" });
          }
          for (let k = 0; k < data[i].length; k++) {
            this.getCityName(data[i][k].location).then((name) => {
              this.pathInfo[i][k].path = name;
            });
          }
          this.dataInfo[i] = data[i];
        }
      }
    },
    keywordsSearch(val) {
      if (val) {
        let _this = this;
        this.cityList = [];
        this.searchOptions.pageIndex = 1;
        this.placeSearch = new this.aMap.PlaceSearch(this.searchOptions);
        this.placeSearch.search(val, function (status, result) {
          if (status === "complete") {
            let data = result.poiList;
            let countNum = Math.ceil(data.count / data.pageSize);
            _this.cityList.push(...data.pois);
            if (countNum > 1) {
              _this.countResult(val, countNum);
            }
          }
        });
      }
    },
    countResult(val, countNum) {
      for (let i = 1; i < countNum; i++) {
        this.mergeList(val, i + 1);
      }
    },
    mergeList(val, page) {
      let _this = this;
      this.placeSearch = new this.aMap.PlaceSearch({
        city: "全国",
        pageIndex: page,
        pageSize: 50,
      });
      this.placeSearch.search(val, function (status, result) {
        if (status === "complete") {
          let data = result.poiList;
          _this.cityList.push(...data.pois);
        }
      });
    },
    initMap() {
      window._AMapSecurityConfig = {
        securityJsCode: "f5c564b72aea4ec517dd3ea4d86c78f8",
      };
      AMapLoader.load({
        key: "8e6281c734527f3c062fa0ec7d642731",
        version: "1.4.15",
        plugins: [
          "AMap.Geocoder",
          "AMap.DragRoute",
          "AMap.Driving",
          "AMap.DistrictSearch",
          "AMap.PlaceSearch",
          "AMap.AutoComplete",
          "AMap.AdvancedInfoWindow",
          "AMap.Geolocation",
          "AMap.MapType",
          "AMap.Scale",
          "AMap.ToolBar",
          "AMap.ElasticMarker",
        ],
      })
        .then((AMap) => {
          this.aMap = AMap;
          this.map = new this.aMap.Map("map", {
            resizeEnable: true,
            center: [105, 38],
            zoom: 4.7,
          });
          let toolbar = new this.aMap.ToolBar();
          this.map.addControl(toolbar);
          this.geocoder = new AMap.Geocoder({
            radius: 10000,
          });
          this.driving = new AMap.Driving({
            map: this.map,
          });
        })
        .catch((e) => {
          this.$message.error("网络错误");
        });
    },
  },
  mounted() {
    this.initMap();
  },
  beforeDestroy() {
    this.map.clearMap();
    this.map.destroy();
  },
};
</script>
<style lang='scss' scoped>
.container {
  color: #606266;
  display: grid;
  grid-template-columns: 360px auto;
  height: 100%;

  .dialog-wrapper {
    margin-top: 6%;
    .route-type {
      width: 100%;
    }
    .time-wrapper {
      width: 100%;
    }
    .little-wrapper {
      display: inline-block;
      width: max-content;

      .unit {
        padding: 0 12px;
      }
      .little-input {
        width: 86px;
      }
    }

    .dialog-title {
      font-size: 20px;
      margin-bottom: 32px;
    }
  }

  .map-data-list {
    display: grid;
    grid-template-rows: 360px 1px auto;
    height: 100%;
    border-right: solid 1px #e6ebfb;

    .search-wrapper {
      height: 100%;
      padding: 28px 0;
      overflow:hidden;
      overflow-y:auto;
      .btn-wrapper {
        width: 100%;
        padding: 0 8%;
        display: grid;
        grid-template-columns: repeat(3, 1fr);
      }
    }

    .line {
      height: 1px;
      background: #e6ebfb;
    }

    .data-list {
      cursor: pointer;
      height: calc(100vh - 412px);
      font-size: 14px;
      overflow: hidden;
      overflow-y: auto;

      .title {
        text-align: center;
        padding: 12px 0;
      }

      .path-title {
        padding: 12px;
      }

      .location-desc {
        padding: 12px;
      }

      .data-wrapper {
        border-bottom: solid 1px #e6ebfb;
      }
    }
  }

  .map-wrapper {
    height: 100%;

    #map {
      width: 100%;
      height: 100%;
      margin: 0 auto;
    }
  }
}

::v-deep .el-form-item__label {
  font-weight: 500;
}

::v-deep .add-icon {
  cursor: pointer;
  color: #409eff;
  margin-left: 6px;
  font-weight: bold;
  font-size: 18px;
}
</style>